from core.db.dbeaver_pool import DbeaverPool
from core.proxy_validate.httpbin_validator import check_proxy
from settings import MAX_WORKERS_OF_THREAD_POOL, TEST_PROXIES_INTERVAL
from concurrent.futures import ThreadPoolExecutor
from utils.log import logger
import schedule
import time


class ProxyTest(object):
    def __init__(self):
        self.dbeaver_pool = DbeaverPool()

    def run(self):
        # 从数据库获取所有代理ip
        with ThreadPoolExecutor(max_workers=MAX_WORKERS_OF_THREAD_POOL) as pool:
            args = [proxy for proxy in self.dbeaver_pool.all_proxies()]
            pool.map(self.__check_one_proxy, args)
        logger.info("The 'run' function call ends.")

    def __check_one_proxy(self, proxy):
        proxy = check_proxy(proxy)
        check, db_proxy = self.dbeaver_pool.is_exist(proxy.ip)
        # 检测ip可用性
        if proxy.speed == -1:
            db_proxy.score -= 1
            if db_proxy.score == 0:
                self.dbeaver_pool.delete_one(db_proxy)
            else:
                self.dbeaver_pool.update_one(db_proxy)
        else:
            self.dbeaver_pool.update_one(proxy)

    @classmethod
    def start(cls):
        proxy_tester = cls()
        proxy_tester.run()
        schedule.every(TEST_PROXIES_INTERVAL).hours.do(proxy_tester.run)
        while True:
            schedule.run_pending()
            time.sleep(10)


if __name__ == '__main__':
    ProxyTest.start()
